﻿using Microsoft.AspNetCore.Http;

namespace Common
{
    /// <summary>
    /// 文件上传信息
    /// </summary>
    public class FileUploadInfo
    {
        /// <summary>
        /// 文件名称
        /// </summary>
        public string? FileName { get; set; }
        /// <summary>
        /// 状态
        /// </summary>
        public string? Status { get; set; }
        /// <summary>
        /// 消息
        /// </summary>
        public string? Message { get; set; }
    }
    /// <summary>
    /// 文件帮助
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 文件夹根目录
        /// </summary>
        private readonly string RootDirectory = "FileLibrary";
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="files"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<FileUploadInfo> UploadFile(List<IFormFile> files, int userId)
        {
            List<FileUploadInfo> fileUploadInfo = new();
            try
            {
                foreach (var file in files)
                {
                    //获取文件名（包含后缀名）
                    string fileName = file.FileName;
                    //判断文件大小
                    if (file.Length > 1024 * 1024 * 10 || file.Length < 0)
                    {
                        fileUploadInfo.Add(new FileUploadInfo()
                        {
                            FileName = fileName,
                            Status = "Error",
                            Message = "文件大小超过10M"
                        });
                        continue;
                    }
                    //判断文件类型
                    if (!(IsImageFile(file) || IsVideoFile(file) || IsExcelFile(file)))
                    {
                        fileUploadInfo.Add(new FileUploadInfo()
                        {
                            FileName = fileName,//这个文件名是原来用户电脑上的文件名
                            Status = "Error",
                            Message = "文件类型不支持"
                        });
                        continue;
                    }
                    //获取文件后缀
                    string fileExt = Path.GetExtension(fileName);
                    string newFileName = $"userId={userId}-{Guid.NewGuid()}{fileExt}";
                    //获取储存的文件夹名称
                    var folder = GetFolderNameByFileType(fileName);
                    //拼接文件夹路径
                    string filePath = Path.Combine(Directory.GetCurrentDirectory(), RootDirectory, folder);
                    //判断文件路径是否存在
                    if (!Directory.Exists(filePath))
                    {
                        //如果不存在就创建这个文件夹
                        Directory.CreateDirectory(filePath);
                    }
                    //拼接完整的文件路径
                    filePath = Path.Combine(filePath, newFileName);
                    //保存文件
                    using (FileStream fs = new(filePath, FileMode.Create))
                    {
                        //把文件写入到流中
                        file.CopyTo(fs);
                        //清空缓冲区
                        fs.Flush();
                    }
                    //如果保存成功，把文件信息加入集合，继续下一个文件
                    fileUploadInfo.Add(new FileUploadInfo()
                    {
                        FileName = newFileName,
                        Status = "Success",
                        Message = "上传成功",
                    });
                }
                return fileUploadInfo;
            }
            catch
            {
                return fileUploadInfo;
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName">下载的文件名</param>
        /// <returns></returns>
        public FileStream? DownloadFile(string fileName)
        {
            try
            {
                //获取储存的文件夹名称
                string folder = GetFolderNameByFileType(fileName);
                //拼接完整的文件路径
                string filePath = Path.Combine(Directory.GetCurrentDirectory(), RootDirectory, folder, fileName);
                return new FileStream(filePath, FileMode.Open);
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 是否为图片文件
        /// </summary>
        /// <param name="file">文件信息</param>
        /// <returns></returns>
        public static bool IsImageFile(IFormFile file)
        {
            string[] allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };
            string fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            return allowedExtensions.Contains(fileExtension);
        }
        /// <summary>
        /// 是否为视频文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool IsVideoFile(IFormFile file)
        {
            string[] allowedExtensions = new[] { ".mp3", ".mp4" };
            string fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            return allowedExtensions.Contains(fileExtension);
        }
        /// <summary>
        /// 是否为Excel文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool IsExcelFile(IFormFile file)
        {
            string[] allowedExtensions = new[] { ".xls", ".xlsx" };
            string fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            return allowedExtensions.Contains(fileExtension);
        }
        /// <summary>
        /// 获取文件夹名称(ByFileType)
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetFolderNameByFileType(string fileName)
        {
            //获取文件后缀
            string fileExt = Path.GetExtension(fileName);
            string folder = "OrdinaryFile";
            switch (fileExt)
            {
                case ".jpg":
                case ".jpeg":
                case ".png":
                case ".gif":
                    folder = "Image";
                    break;
                case ".mp3":
                    folder = "Music";
                    break;
                case ".mp4":
                    folder = "Video";
                    break;
                case ".xls":
                case ".xlsx":
                    folder = "Excel";
                    break;
            }
            return folder;
        }
        /// <summary>
        /// 获取ContentType(ByFileType)
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetContentType(string fileName)
        {
            //获取文件后缀
            string fileExt = Path.GetExtension(fileName);
            switch (fileExt)
            {
                case ".jpg":
                case ".jpeg":
                    return "image/jpeg";
                case ".png":
                    return "image/png";
                case ".gif":
                    return "image/gif";
                case ".bmp":
                    return "image/bmp";
                case ".txt":
                    return "text/plain";
                case ".doc":
                    return "application/msword";
                case ".docx":
                    return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                case ".mp3":
                    return "audio/mpeg";
                case ".mp4":
                    return "video/mp4";
                case ".xls":
                    return "application/vnd.ms-excel";
                case ".xlsx":
                    return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                default:
                    break;
            }
            return "application/octet-stream";
        }
    }
}
